#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/fb.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

#include <encoding_manager.h>
#include <fonts_manager.h>





// 返回值：获得的unicode需要多少字节来表示；返回0表示文件结束；返回-1表示出错
static int utf8_GetUnicodeFromBuffer(unsigned char *bufstart, unsigned char *bufend, unsigned int *unicode)
{
    if (bufstart >= bufend) 
    {
        printf("out of range\n");
        return 0; // 文件结束
    }

    unsigned char first_byte = *bufstart;
    int byte_count = 0;

    // 根据第一字节的值来判断字符的字节长度
    if (first_byte <= 0x7F) {
        // 1 字节的字符 (ASCII)
        *unicode = first_byte;
        byte_count = 1;
    }
    else if ((first_byte >= 0xC0) && (first_byte <= 0xDF)) {
        // 2 字节字符: 110xxxxx 10xxxxxx
        if (bufstart + 1 >= bufend) return -1; // 解码错误
        unsigned char second_byte = *(bufstart + 1);
        // 提取第一个字节的低5位和第二字节的低6位，最后拼在一起
        *unicode = ((first_byte & 0x1F) << 6) | (second_byte & 0x3F);
        byte_count = 2;
    }
    else if ((first_byte >= 0xE0) && (first_byte <= 0xEF)) {
        // 3 字节字符: 1110xxxx 10xxxxxx 10xxxxxx
        if (bufstart + 2 >= bufend) return -1; // 解码错误
        unsigned char second_byte = *(bufstart + 1);
        unsigned char third_byte = *(bufstart + 2);
        *unicode = ((first_byte & 0x0F) << 12) | ((second_byte & 0x3F) << 6) | (third_byte & 0x3F);
        byte_count = 3;
    }
    else if ((first_byte >= 0xF0) && (first_byte <= 0xF7)) {
        // 4 字节字符: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
        if (bufstart + 3 >= bufend) return -1; // 解码错误
        unsigned char second_byte = *(bufstart + 1);
        unsigned char third_byte = *(bufstart + 2);
        unsigned char fourth_byte = *(bufstart + 3);
        *unicode = ((first_byte & 0x07) << 18) | ((second_byte & 0x3F) << 12) | ((third_byte & 0x3F) << 6) | (fourth_byte & 0x3F);
        byte_count = 4;
    }
    else {
        return -1; // 无效的 UTF-8 字节
    }

    // 返回字节数
    printf("UTF8 to Unicode done\n");
    return byte_count;
}


// 通过BOM判断是否支持utf8编码
static int SupportUtf8(unsigned char *bufhead)
{
    // UTF-8的BOM是3字节：0xEF 0xBB 0xBF
    const unsigned char utf8_bom[] = {0xEF, 0xBB, 0xBF};
    
    // 检查前3个字节是否匹配UTF-8 BOM
    return (bufhead[0] == utf8_bom[0] && 
            bufhead[1] == utf8_bom[1] && 
            bufhead[2] == utf8_bom[2]);
}


static EncodingOpr utf8_EncodingOpr =
{
    .name = "utf8",
    .iHeadLen = 3,
    .GetUnicodeFromBuffer = utf8_GetUnicodeFromBuffer,
    .Support = SupportUtf8,
};



void RegisterUtf8(void)
{
    RegisterEncodingOpr(&utf8_EncodingOpr);
}



// 为utf8_EncodingOpr设置支持utf8编码格式的字体
int SetSupportFontForUtf8(void)
{
    AddFontOprToEncodingOpr(GetFontOprByName("ft"), &utf8_EncodingOpr);
    AddFontOprToEncodingOpr(GetFontOprByName("ascii"), &utf8_EncodingOpr);
    AddFontOprToEncodingOpr(GetFontOprByName("hzk"), &utf8_EncodingOpr);
    return 0;
}




